package au.edu.qut.bpm.genbinder.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.List;
import java.util.Set;

import javax.swing.JPanel;
import au.edu.qut.bpm.genbinder.models.Activity;
import au.edu.qut.bpm.genbinder.models.Case;
import au.edu.qut.bpm.genbinder.models.ConcreteEventLog;

public class CasePanel extends JPanel {
	private static final long serialVersionUID = -7987953869910163289L;

	private ConcreteEventLog log;
	private Case oCase;
	private List<Set<Activity>> violations;

	// TODO: The whole viz stuff can be made prettier and better engineered as well
	
	public CasePanel(ConcreteEventLog dlog, Case oCase,
			List<Set<Activity>> violations) {
		Dimension d = this.getSize();
		d.height = CaseListPanel.ROWHEIGHT;
		this.setSize(d);
		this.setPreferredSize(d);

		this.log = dlog;
		this.oCase = oCase;
		this.violations = violations;
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(Color.black);
		g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
		g.setFont(g.getFont().deriveFont(10f));

		g.setColor(Color.red);
		int border = 4;
		int xl = (int) Math.floor((double) (log.getCaseArrival(oCase) - CaseListPanel.TIMESHOWFROM)
				* CaseListPanel.TIMETOPIXELS);
		int xm = (int) Math.floor((double) (log.getCaseEnd(oCase) - CaseListPanel.TIMESHOWFROM)
				* CaseListPanel.TIMETOPIXELS);
		g.fillRect(xl, 1, xm - xl + 1, CaseListPanel.ROWHEIGHT - 2);

		if (CaseListPanel.TIMETOPIXELS >= 1) {
			g.setColor(Color.black);
			for (int x = 0; x <= this.getWidth() / CaseListPanel.TIMETOPIXELS; x++) {
				int xr = (int) (x * CaseListPanel.TIMETOPIXELS);
				g.fillRect(xr, 0, 1, CaseListPanel.ROWHEIGHT);
			}
		}

		for (Activity act : oCase.getActivities()) {
			int x1 = (int) Math.floor((double) (log.getActivityStart(act) - CaseListPanel.TIMESHOWFROM)
					* CaseListPanel.TIMETOPIXELS);
			int x2 = (int) Math.floor((double) (log.getActivityEnd(act) - CaseListPanel.TIMESHOWFROM)
					* CaseListPanel.TIMETOPIXELS);
			g.setColor(Color.blue);
			g.drawRect(x1, border, x2 - x1, CaseListPanel.ROWHEIGHT - border * 2);
			
			Color fillColor = Color.white;
			if (violations != null) {
				if (violations.get(0).contains(act))//overlap
					fillColor = Color.cyan;
				if (violations.get(1).contains(act))//misorder
					fillColor = Color.orange;
				if (violations.get(2).contains(act))//resourceclash
					fillColor = Color.pink;
				if (violations.get(3).contains(act))//invalidresource
					fillColor = Color.gray;
			}
			
			g.setColor(fillColor);
			g.fillRect(x1 + 1, border + 1, x2 - x1 - 1, CaseListPanel.ROWHEIGHT - border * 2 - 1);

			g.setColor(Color.black);
			g.drawString(act.toString(), x1 + border, border + 8);
			g.drawString(act.getTask() + "  @  "
					+ log.getActivityResources(act).toString(), x1 + border, border + 18);
		}
	}

}
